<template>
  <div class="user-management-container">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchQuery"
        placeholder="请输入用户名/邮箱"
        clearable
        style="width: 200px; margin-right: 10px"
        @clear="handleSearchClear"
      />
      <el-button
        type="primary"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedIds.length === 0"
        @click="batchDelete"
      >
        批量删除
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        style="margin-left: auto"
        @click="showAddDialog"
      >
        添加用户
      </el-button>
    </div>

    <!-- 用户数据表格 -->
    <!-- 1.绑定当前页数据 -->
    <!-- 2.显示边框 -->
    <!-- 3.宽度100%，上边距20px -->
    <!-- 4.表头样式 -->
    <!-- 5.浅灰色背景 -->
    <!-- 6.深灰色文字 -->
    <!-- 7.加粗 -->
    <!-- 8.选择项变化事件 -->
    <el-table
      :data="currentPageData"
      border
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 'bold'
      }"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选列 -->
      <!-- 1.多选框列 -->
      <!-- 2.固定宽度 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />

      <!-- ID列 -->
      <!-- 1.绑定id字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <!-- 4.固定宽度 -->
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      />

      <!-- 用户名列 -->
      <!-- 1.绑定username字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        prop="username"
        label="用户名"
        align="center"
      />

      <!-- 邮箱列 -->
      <!-- 1.绑定email字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        prop="email"
        label="邮箱"
        align="center"
      />

      <!-- 手机号列 -->
      <!-- 1.绑定phone字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <el-table-column
        prop="phone"
        label="手机号"
        align="center"
      />

      <!-- 状态列 -->
      <!-- 1.绑定status字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <!-- 4.自定义模板显示开关 -->
      <el-table-column
        prop="status"
        label="状态"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 创建时间列 -->
      <!-- 1.绑定createTime字段 -->
      <!-- 2.列标题 -->
      <!-- 3.居中对齐 -->
      <!-- 4.固定宽度 -->
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width="180"
      />

      <!-- 操作列 -->
      <!-- 1.列标题 -->
      <!-- 2.居中对齐 -->
      <!-- 3.固定宽度 -->
      <el-table-column
        label="操作"
        align="center"
        width="180"
      >
        <!-- 自定义列模板 -->
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <!-- 1.小尺寸按钮 -->
          <!-- 2.点击事件，传入当前行数据 -->
          <el-button
            size="mini"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>

          <!-- 删除按钮 -->
          <!-- 1.小尺寸按钮 -->
          <!-- 2.红色警示按钮 -->
          <!-- 3.点击事件，传入当前行id -->
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 - 左下角 -->
    <div class="pagination-container left">
      <span>共{{ filteredUserList.length }}条</span>
      <el-select
        v-model="pagination.pageSize"
        size="mini"
        style="width: 100px; margin: 0 15px"
        @change="handleSizeChange"
      >
        <el-option
          v-for="item in [10, 20, 30, 50]"
          :key="item"
          :label="`${item}条/页`"
          :value="item"
        />
      </el-select>
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        layout="prev, pager, next, jumper"
        :total="filteredUserList.length"
        @current-change="handleCurrentChange"
      />
      <div class="page-jump" />
    </div>

    <!-- 添加用户对话框 - 无遮罩层 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="500px"
      :modal="false"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="addForm.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter.native="confirmAdd"
          />
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input
            v-model="addForm.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter.native="confirmAdd"
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="phone"
        >
          <el-input
            v-model="addForm.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter.native="confirmAdd"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="addForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="confirmAdd"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="500px"
      :modal="false"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="editForm.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter.native="confirmEdit"
          />
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input
            v-model="editForm.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter.native="confirmEdit"
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="phone"
        >
          <el-input
            v-model="editForm.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter.native="confirmEdit"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="confirmEdit"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

// import $ from 'jquery'

export default {
  data () {
    return {
      searchQuery: '',
      selectedIds: [],
      addDialogVisible: false,
      editDialogVisible: false,
      jumpPage: 1,
      activeFilter: null, // 新增：存储当前筛选条件
      userList: [
        { id: 1, username: '用户1', email: 'user1@example.com', phone: '13800138001', status: true, createTime: '2023-01-15 10:30:00' },
        { id: 2, username: '用户2', email: 'user2@example.com', phone: '13800138002', status: true, createTime: '2023-01-16 11:20:00' },
        { id: 3, username: '用户3', email: 'user3@example.com', phone: '13800138003', status: false, createTime: '2023-01-17 14:15:00' },
        { id: 4, username: '用户4', email: 'user4@example.com', phone: '13800138004', status: true, createTime: '2023-01-18 09:45:00' },
        { id: 5, username: '用户5', email: 'user5@example.com', phone: '13800138005', status: true, createTime: '2023-01-19 16:30:00' },
        { id: 6, username: '用户6', email: 'user6@example.com', phone: '13800138006', status: false, createTime: '2023-01-20 10:20:00' },
        { id: 7, username: '用户7', email: 'user7@example.com', phone: '13800138007', status: true, createTime: '2023-01-21 13:10:00' },
        { id: 8, username: '用户8', email: 'user8@example.com', phone: '13800138008', status: true, createTime: '2023-01-22 15:25:00' },
        { id: 9, username: '用户9', email: 'user9@example.com', phone: '13800138009', status: true, createTime: '2023-01-23 11:40:00' },
        { id: 10, username: '用户10', email: 'user10@example.com', phone: '13800138010', status: false, createTime: '2023-01-24 09:15:00' },
        { id: 11, username: '用户11', email: 'user11@example.com', phone: '13800138011', status: true, createTime: '2023-01-25 14:50:00' },
        { id: 12, username: '用户12', email: 'user12@example.com', phone: '13800138012', status: true, createTime: '2023-01-26 10:30:00' },
        { id: 13, username: '用户13', email: 'user13@example.com', phone: '13800138013', status: false, createTime: '2023-01-27 16:20:00' },
        { id: 14, username: '用户14', email: 'user14@example.com', phone: '13800138014', status: true, createTime: '2023-01-28 11:10:00' },
        { id: 15, username: '用户15', email: 'user15@example.com', phone: '13800138015', status: true, createTime: '2023-01-29 09:30:00' },
        { id: 16, username: '用户16', email: 'user11@example.com', phone: '13800138011', status: true, createTime: '2023-01-25 14:50:00' },
        { id: 17, username: '用户17', email: 'user12@example.com', phone: '13800138012', status: true, createTime: '2023-01-26 10:30:00' },
        { id: 18, username: '用户18', email: 'user13@example.com', phone: '13800138013', status: false, createTime: '2023-01-27 16:20:00' },
        { id: 19, username: '用户19', email: 'user14@example.com', phone: '13800138014', status: true, createTime: '2023-01-28 11:10:00' },
        { id: 20, username: '用户20', email: 'user15@example.com', phone: '13800138015', status: true, createTime: '2023-01-29 09:30:00' }
      ],
      loading: false, // 新增加载状态
      pagination: {
        currentPage: 1,
        pageSize: 10
      },
      addForm: {
        username: '',
        email: '',
        phone: '',
        status: true
      },
      editForm: {
        id: 0,
        username: '',
        email: '',
        phone: '',
        status: true,
        createTime: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    filteredUserList () {
      if (!this.activeFilter) return this.userList // 未查询时显示全部
      return this.userList.filter(user =>
        user.username.toLowerCase().includes(this.activeFilter.toLowerCase()) ||
        user.email.toLowerCase().includes(this.activeFilter.toLowerCase()) ||
        user.phone.includes(this.activeFilter)
      )
    },
    currentPageData () {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredUserList.slice(start, end)
    }
  },
  // created () {
  //   this.fetchUserList() // 组件创建时获取用户列表
  // },
  // methods: {
  //   // 获取用户列表
  //   fetchUserList () {
  //     this.loading = true
  //     $.ajax({
  //       url: 'http://localhost:3000/api/users',
  //       type: 'GET',
  //       dataType: 'json',
  //       success: (response) => {
  //         if (response.code === 200) {
  //           this.userList = response.data
  //         } else {
  //           this.$message.error(response.message || '获取用户列表失败')
  //         }
  //       },
  //       error: (xhr, status, error) => {
  //         this.$message.error('请求失败: ' + error)
  //       },
  //       complete: () => {
  //         this.loading = false
  //       }
  //     })
  //   },

  //   // 添加用户
  //   confirmAdd () {
  //     this.$refs.addForm.validate(valid => {
  //       if (valid) {
  //         this.loading = true
  //         $.ajax({
  //           url: 'http://localhost:3000/api/users',
  //           type: 'POST',
  //           contentType: 'application/json',
  //           data: JSON.stringify(this.addForm),
  //           success: (response) => {
  //             if (response.code === 200) {
  //               this.$message.success('添加成功')
  //               this.addDialogVisible = false
  //               this.fetchUserList() // 刷新列表
  //             } else {
  //               this.$message.error(response.message || '添加失败')
  //             }
  //           },
  //           error: (xhr, status, error) => {
  //             this.$message.error('请求失败: ' + error)
  //           },
  //           complete: () => {
  //             this.loading = false
  //           }
  //         })
  //       }
  //     })
  //   },

  //   // 编辑用户
  //   confirmEdit () {
  //     this.$refs.editForm.validate(valid => {
  //       if (valid) {
  //         this.loading = true
  //         $.ajax({
  //           url: `http://localhost:3000/api/users/${this.editForm.id}`,
  //           type: 'PUT',
  //           contentType: 'application/json',
  //           data: JSON.stringify(this.editForm),
  //           success: (response) => {
  //             if (response.code === 200) {
  //               this.$message.success('修改成功')
  //               this.editDialogVisible = false
  //               this.fetchUserList() // 刷新列表
  //             } else {
  //               this.$message.error(response.message || '修改失败')
  //             }
  //           },
  //           error: (xhr, status, error) => {
  //             this.$message.error('请求失败: ' + error)
  //           },
  //           complete: () => {
  //             this.loading = false
  //           }
  //         })
  //       }
  //     })
  //   },

  //   // 删除用户
  //   handleDelete (row) {
  //     this.$confirm(`确定删除用户 ${row.username}?`, '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning'
  //     }).then(() => {
  //       this.loading = true
  //       $.ajax({
  //         url: `http://localhost:3000/api/users/${row.id}`,
  //         type: 'DELETE',
  //         success: (response) => {
  //           if (response.code === 200) {
  //             this.$message.success('删除成功')
  //             this.fetchUserList() // 刷新列表
  //           } else {
  //             this.$message.error(response.message || '删除失败')
  //           }
  //         },
  //         error: (xhr, status, error) => {
  //           this.$message.error('请求失败: ' + error)
  //         },
  //         complete: () => {
  //           this.loading = false
  //         }
  //       })
  //     }).catch(() => {
  //       this.$message.info('已取消删除')
  //     })
  //   },

  //   // 批量删除
  //   batchDelete () {
  //     if (this.selectedIds.length === 0) {
  //       this.$message.warning('请至少选择一条数据')
  //       return
  //     }
  //     this.$confirm('确定删除选中的用户吗?', '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning'
  //     }).then(() => {
  //       this.loading = true
  //       $.ajax({
  //         url: 'http://localhost:3000/api/users/batch',
  //         type: 'DELETE',
  //         contentType: 'application/json',
  //         data: JSON.stringify({ ids: this.selectedIds }),
  //         success: (response) => {
  //           if (response.code === 200) {
  //             this.$message.success('删除成功')
  //             this.selectedIds = []
  //             this.fetchUserList() // 刷新列表
  //           } else {
  //             this.$message.error(response.message || '删除失败')
  //           }
  //         },
  //         error: (xhr, status, error) => {
  //           this.$message.error('请求失败: ' + error)
  //         },
  //         complete: () => {
  //           this.loading = false
  //         }
  //       })
  //     }).catch(() => {
  //       this.$message.info('已取消删除')
  //     })
  //   },

  //   // 修改用户状态
  //   handleStatusChange (row) {
  //     this.loading = true
  //     $.ajax({
  //       url: `/api/users/${row.id}/status`,
  //       type: 'PATCH',
  //       contentType: 'application/json',
  //       data: JSON.stringify({ status: row.status }),
  //       success: (response) => {
  //         if (response.code === 200) {
  //           this.$message.success(`用户 ${row.username} 已${row.status ? '启用' : '禁用'}`)
  //         } else {
  //           // 操作失败时恢复原状态
  //           row.status = !row.status
  //           this.$message.error(response.message || '状态修改失败')
  //         }
  //       },
  //       error: (xhr, status, error) => {
  //         // 请求失败时恢复原状态
  //         row.status = !row.status
  //         this.$message.error('请求失败: ' + error)
  //       },
  //       complete: () => {
  //         this.loading = false
  //       }
  //     })
  //   },

  //   // 搜索用户
  //   handleSearch () {
  //     this.loading = true
  //     $.ajax({
  //       url: '/api/users/search',
  //       type: 'GET',
  //       data: { keyword: this.searchQuery },
  //       dataType: 'json',
  //       success: (response) => {
  //         if (response.code === 200) {
  //           this.activeFilter = this.searchQuery
  //           this.userList = response.data
  //           this.pagination.currentPage = 1
  //         } else {
  //           this.$message.error(response.message || '搜索失败')
  //         }
  //       },
  //       error: (xhr, status, error) => {
  //         this.$message.error('请求失败: ' + error)
  //       },
  //       complete: () => {
  //         this.loading = false
  //       }
  //     })
  //   }
  // }
  methods: {
    handleSearch () {
      // 只有点击查询时才设置筛选条件
      this.activeFilter = this.searchQuery
      this.pagination.currentPage = 1
    },
    handleSearchClear () {
      this.searchQuery = ''
      this.activeFilter = null // 清除筛选条件
      this.pagination.currentPage = 1
    },
    handleSelectionChange (selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    // 编辑按钮点击事件
    handleEdit (row) {
      this.showEditDialog(row)
    },
    confirmEdit () {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 找到原用户并更新数据
          const index = this.userList.findIndex(user => user.id === this.editForm.id)
          if (index !== -1) {
            this.userList.splice(index, 1, { ...this.editForm })
            this.editDialogVisible = false
            this.$message.success('修改成功')
          }
        }
      })
    },
    batchDelete () {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.$confirm('确定删除选中的用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.userList = this.userList.filter(user => !this.selectedIds.includes(user.id))
        this.selectedIds = []
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    showAddDialog () {
      this.addDialogVisible = true
      this.$nextTick(() => {
        this.resetForm('addForm')
      })
    },
    showEditDialog (row) {
      this.editForm = JSON.parse(JSON.stringify(row))
      this.editDialogVisible = true
    },
    resetForm (formName) {
      this.$refs[formName]?.resetFields()
      if (formName === 'addForm') {
        this.addForm.status = true
      }
    },
    confirmAdd () {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          const newUser = {
            id: this.userList.length + 1,
            ...this.addForm,
            createTime: new Date().toLocaleString()
          }
          this.userList.push(newUser)
          this.addDialogVisible = false
          this.$message.success('添加成功')

          // 如果当前页未满，则保持在当前页
          // 如果当前页已满，则跳转到最后一页
          const currentPageItemCount = this.currentPageData.length
          if (currentPageItemCount >= this.pagination.pageSize) {
            const totalPages = Math.ceil(this.filteredUserList.length / this.pagination.pageSize)
            this.pagination.currentPage = totalPages
          }
        }
      })
    },
    handleDelete (row) {
      this.$confirm(`确定删除用户 ${row.username}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.userList = this.userList.filter(user => user.id !== row.id)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleStatusChange (row) {
      this.$message.success(`用户 ${row.username} 已${row.status ? '启用' : '禁用'}`)
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
    },
    handleJumpPage () {
      const page = parseInt(this.jumpPage)
      const maxPage = Math.ceil(this.filteredUserList.length / this.pagination.pageSize)
      if (page > 0 && page <= maxPage) {
        this.pagination.currentPage = page
      } else {
        this.$message.warning(`请输入1-${maxPage}之间的页码`)
      }
    }
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.operation-bar {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

/* 分页容器调整到左下角 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.pagination-container .el-pagination {
  margin: 0 15px;
}

.page-jump {
  display: flex;
  align-items: center;
  margin-left: 15px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  margin-top: 20px;
}

.el-table--border {
  border: 1px solid #EBEEF5;
}

.el-table th > .cell {
  font-weight: bold;
}

/* 对话框无遮罩层样式 */
.el-dialog__wrapper {
  background-color: transparent !important;
}
</style>
